package controller

import (
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type UserLogin struct {
	Code string `json:"code"`
	Url  string `json:"url"`
}

// UserInfo 用户信息
type UserInfo struct {
	AccessToken string `json:"access_token"`
	OpenId      string `json:"open_id"`
}

// AuthLogin 登录 授权URL
func (u UserLogin) AuthLogin(context *gin.Context) {
	//code := u.Code

	//getAccessTokenUrl := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, appSecret, code)
	//resp, err := http.Get(getAccessTokenUrl)
	//if err != nil {
	//	context.JSON(500, "请求获取access_token失败")
	//}
	//
	//defer resp.Body.Close()
	//var accessTokenResponse map[string]string
	//if err := json.NewDecoder(resp.Body).Decode(&accessTokenResponse); err != nil {
	//	context.JSON(500, "解析access_token出错")
	//}
	//context.JSON(200, accessTokenResponse)
}

// generateSignature 生成签名
func generateSignature(url, timestamp string, nonceStr string, jsapiTicket string) string {
	stringToSign := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", jsapiTicket, nonceStr, timestamp, url)
	h := sha1.New()
	h.Write([]byte(stringToSign))
	return hex.EncodeToString(h.Sum(nil))
}

// generateNonceStr 生成随机字符串
func generateNonceStr() string {
	return fmt.Sprintf("%d", time.Now().UnixNano())
}

// GetUserInfo 获取用户信息
func (u UserInfo) GetUserInfo(context *gin.Context) {
	infoUrl := fmt.Sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN")

	resp, err := http.Get(infoUrl)
	if err != nil {
		context.JSON(500, "获取用户信息错误")
	}
	defer resp.Body.Close()
	var userInfoRes map[string]string
	if err := json.NewDecoder(resp.Body).Decode(&userInfoRes); err != nil {
		context.JSON(500, "解析用户信息出错")
	}
	context.JSON(200, userInfoRes)
}
